<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AI Chat</title>
    <script>
        function sendMessage() {
            const userInput = document.getElementById("message").value;
            if (!userInput.trim()) return;

            const chatBox = document.getElementById("chat");
            const userEntry = document.createElement("div");
            userEntry.innerHTML = `<b>You:</b> ${userInput}`;
            chatBox.appendChild(userEntry);

            const aiEntry = document.createElement("div");
            aiEntry.innerHTML = `<b>AI:</b> <span class="ai-response"></span>`;
            chatBox.appendChild(aiEntry);

            document.getElementById("message").value = "";

            const sessionId = localStorage.getItem("sid") || crypto.randomUUID();
            localStorage.setItem("sid", sessionId);

            const url = `/chat2?sessionId=${sessionId}&userMessage=${encodeURIComponent(userInput)}`;
            const eventSource = new EventSource(url);

            const aiResponseSpan = aiEntry.querySelector(".ai-response");

            eventSource.onmessage = function(event) {
                aiResponseSpan.innerHTML += event.data;
                chatBox.scrollTop = chatBox.scrollHeight; // 自动滚动到底部
            };

            eventSource.onerror = function() {
                eventSource.close();
            };
        }
    </script>
    <style>
        body { font-family: Arial; margin: 20px; }
        #chat { border: 1px solid #ccc; padding: 10px; height: 400px; overflow-y: auto; }
        #message { width: 80%; }
        button { padding: 5px 10px; }
        div { margin: 5px 0; }
    </style>
</head>
<body>
<h2>AI Chat</h2>
<div id="chat"></div>
<input id="message" type="text" placeholder="Say something...">
<button onclick="sendMessage()">Send</button>
</body>
</html>